import json
import threading
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler

import abaloneageprediction


class Abalone:
    def __init__(self, gender, length, dia, height, tweight, tare, vweight, sweight):
        self.gender = 1 if (gender.upper() == 'M') else (-1 if gender.upper() == 'F' else 0)
        self.length = float(length)
        self.dia = float(dia)
        self.height = float(height)
        self.tweight = float(tweight)
        self.tare = float(tare)
        self.vweight = float(vweight)
        self.sweight = float(sweight)

    def getAge(self):
        ex = [self.length, self.dia, self.height, self.tweight, self.tare, self.vweight, self.sweight, self.gender]
        return abaloneageprediction.predict_age(ex);

class RequestHandler(BaseHTTPRequestHandler):
    # Borrowing from https://gist.github.com/nitaku/10d0662536f37a087e1b
    def _set_headers(self):
        self.send_response(HTTPStatus.OK.value)
        self.send_header('Content-type', 'application/json')
        # Allow requests from any origin, so CORS policies don't
        # prevent local development.
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write(json.dumps({'success': True}).encode('utf-8'))

    def do_POST(self):
        t = threading.currentThread()
        print("Thread ID: " + t.getName() + "\t Thread Name: " + str(t.ident))
        length = int(self.headers.get('content-length'))
        message = json.loads(self.rfile.read(length))
        abalone = Abalone(message["gender"], message["length"], message["dia"],
                          message["height"], message["tweight"], message["tare"], message["vweight"], message["sweight"]);
        self._set_headers()
        self.wfile.write(json.dumps({'success': True, 'weight' : abalone.getAge()}).encode('utf-8'))

    def do_OPTIONS(self):
        # Send allow-origin header for preflight POST XHRs.
        self.send_response(HTTPStatus.NO_CONTENT.value)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST')
        self.send_header('Access-Control-Allow-Headers', 'content-type')
        self.end_headers()